package platform

import (
	"fmt"
	"log"
	"net/http"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/errors"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// UnifiedCardController 统一卡片操作控制器
// 使用platform_handlers来处理不同平台的开卡功能
type UnifiedCardController struct {
	photonpayClient *photonpay.PhotonPayClient
	hlpayClient     *hlPay.HlPayClient
	db              *gorm.DB
	platformManager *integration.PlatformManager
}

// NewUnifiedCardController 创建统一卡片操作控制器实例
func NewUnifiedCardController(photonpayClient *photonpay.PhotonPayClient, hlpayClient *hlPay.HlPayClient) *UnifiedCardController {
	// 使用全局平台管理器
	platformManager := integration.GetGlobalPlatformManager()

	return &UnifiedCardController{
		photonpayClient: photonpayClient,
		hlpayClient:     hlpayClient,
		db:              database.DB,
		platformManager: platformManager,
	}
}

// UserRoleBalance 用户角色和余额信息
type UserRoleBalance struct {
	RoleID  int64
	UserID  int64
	Balance decimal.Decimal
}

// getUserRoleAndBalance 获取用户角色和余额信息
func (c *UnifiedCardController) getUserRoleAndBalance(ctx *gin.Context) (*UserRoleBalance, error) {
	claims, exists := ctx.Get("claims")
	if !exists {
		return nil, errors.NewAppError(http.StatusUnauthorized, "unauthorized", nil)
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		return nil, errors.NewAppError(http.StatusInternalServerError, "invalid_token_claims", nil)
	}

	userID := authClaims.UserID
	roleID := authClaims.RoleID
	var balance decimal.Decimal

	switch roleID {
	case 2: // 普通用户 - 返回0余额
		balance = decimal.Zero
	case 3: // 主账号
		var masterAccount models.MasterAccount
		if err := c.db.Where("user_id = ?", userID).First(&masterAccount).Error; err != nil {
			return nil, errors.NewAppError(http.StatusInternalServerError, "get_master_account_failed", err)
		}
		balance = masterAccount.Balance
	case 5: // 子账号
		var subAccount models.SubAccount
		if err := c.db.Where("user_id = ?", userID).First(&subAccount).Error; err != nil {
			return nil, errors.NewAppError(http.StatusInternalServerError, "get_sub_account_failed", err)
		}
		balance = subAccount.Balance
	}

	return &UserRoleBalance{
		RoleID:  roleID,
		UserID:  userID,
		Balance: balance,
	}, nil
}

// TestBalanceUpdate 测试余额更新功能（仅用于开发测试）
func (c *UnifiedCardController) TestBalanceUpdate(ctx *gin.Context) {
	// 解析测试请求参数
	var req struct {
		UserID    int64  `json:"userId" binding:"required"`
		RoleID    int    `json:"roleId" binding:"required"`
		Amount    string `json:"amount" binding:"required"`
		Operation string `json:"operation" binding:"required,oneof=add deduct"`
		Platform  string `json:"platform" binding:"required,oneof=hlpay photonpay"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 解析金额
	amount, err := decimal.NewFromString(req.Amount)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_amount", fmt.Errorf("invalid amount format"))
		return
	}

	log.Printf("[TestBalanceUpdate] 开始测试余额更新 - 用户ID: %d, 角色ID: %d, 金额: %s, 操作: %s, 平台: %s",
		req.UserID, req.RoleID, amount.String(), req.Operation, req.Platform)

	// 获取账户号（仅用于HlPay平台）
	var accountNo string
	if req.Platform == "hlpay" {
		// 查找用户的矩阵账户
		var userMatrixAccount models.UserMatrixAccount
		if err := c.db.Where("user_id = ? AND platform_type = ?", req.UserID, "hlpay").First(&userMatrixAccount).Error; err == nil {
			// 查找对应的HlPay账户余额记录
			var hlpayAccount models.HlPayAccountBalance
			if err := c.db.Where("owner_no = ?", userMatrixAccount.MatrixAccount).First(&hlpayAccount).Error; err == nil {
				accountNo = hlpayAccount.AccountNo
				log.Printf("[TestBalanceUpdate] 找到HlPay账户: %s, 当前余额: %s",
					hlpayAccount.AccountNo, hlpayAccount.RealTimeBalance.String())
			}
		}
	}

	// 调用余额更新函数
	if err := c.updateBalanceForRole(ctx, req.UserID, req.RoleID, amount, req.Operation, req.Platform, accountNo); err != nil {
		log.Printf("[TestBalanceUpdate] 余额更新失败: %v", err)
		common.Error(ctx, http.StatusInternalServerError, "balance_update_failed", err)
		return
	}

	log.Printf("[TestBalanceUpdate] 余额更新测试成功")

	// 返回成功响应
	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "余额更新测试成功",
			"EN": "Balance update test successful",
			"VN": "Kiểm tra cập nhật số dư thành công",
		},
		"data": gin.H{
			"userId":    req.UserID,
			"roleId":    req.RoleID,
			"amount":    amount.String(),
			"operation": req.Operation,
			"platform":  req.Platform,
			"accountNo": accountNo,
		},
	}

	common.Success(ctx, response)
}
